package com.zly.framework.rbac.config;

import com.zly.framework.rbac.configuration.SysAuthConfiguration;
import com.zly.framework.rbac.filter.CaptchaFilter;
import com.zly.framework.rbac.filter.JwtFilter;
import com.zly.framework.rbac.handler.failed.AccessDeniedExceptionHandler;
import com.zly.framework.rbac.handler.failed.AuthenticationEntryPointHandler;
import com.zly.framework.rbac.handler.failed.LoginFailureHandler;
import com.zly.framework.rbac.handler.success.LoginSuccessHandler;
import com.zly.framework.rbac.utils.JwtUtils;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * SpringSecurity配置
 *
 * @author ZLY
 * @createtime 2024/6/1
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    @Resource
    private UserDetailsService securityUserDetailsServiceImpl;
    @Resource
    private CaptchaFilter captchaFilter;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SysAuthConfiguration sysAuthConfiguration;
    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private LoginFailureHandler loginFailureHandler;
    @Resource
    private AuthenticationConfiguration authenticationConfiguration;
    @Resource
    private AccessDeniedExceptionHandler accessDeniedExceptionHandler;
    @Resource
    private AuthenticationEntryPointHandler authenticationEntryPointHandler;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(securityUserDetailsServiceImpl);  // 提供自定义loadUserByUsername
        authProvider.setPasswordEncoder(passwordEncoder()); // 指定密码编辑器
        return authProvider;
    }

    @Bean(name = "prodSecurityFilterChain")
    @Profile({"prod"})
    public SecurityFilterChain springSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(httpRequests -> {
                    for (String noAuthUrl : sysAuthConfiguration.getUrl().getNoAuth()) {
                        httpRequests.requestMatchers(noAuthUrl).permitAll();
                    }
                    httpRequests.anyRequest().authenticated();
                })
                .formLogin(login -> login
                        .loginPage("/sys/need/login")
                        .loginProcessingUrl("/sys/login")
                        .usernameParameter("username")
                        .passwordParameter("password")
                        .successHandler(loginSuccessHandler)
                        .failureHandler(loginFailureHandler)
                        .permitAll())
                .logout(logout -> logout
                        .logoutUrl("/sys/logout")
                        .invalidateHttpSession(true)
                        .permitAll())
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .exceptionHandling(exception -> exception
                        .accessDeniedHandler(accessDeniedExceptionHandler)
                        .authenticationEntryPoint(authenticationEntryPointHandler))
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilter(new JwtFilter(authenticationManager(), stringRedisTemplate, sysAuthConfiguration, jwtUtils))
                .csrf(AbstractHttpConfigurer::disable)
                .cors(AbstractHttpConfigurer::disable);
        return http.build();
    }

    @Bean(name = "devSecurityFilterChain")
    @Profile({"dev"})
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(httpRequests -> {
                    httpRequests.requestMatchers("/doc.html",
                            "/webjars/**",
                            "/v3/**",
                            "/swagger-resources/**").permitAll();
                    for (String noAuthUrl : sysAuthConfiguration.getUrl().getNoAuth()) {
                        httpRequests.requestMatchers(noAuthUrl).permitAll();
                    }
                    httpRequests.anyRequest().authenticated();
                })
                .formLogin(login -> login
                        .loginPage("/sys/need/login")
                        .loginProcessingUrl("/sys/login")
                        .usernameParameter("username")
                        .passwordParameter("password")
                        .successHandler(loginSuccessHandler)
                        .failureHandler(loginFailureHandler)
                        .permitAll())
                .logout(logout -> logout
                        .logoutUrl("/sys/logout")
                        .invalidateHttpSession(true)
                        .permitAll())
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .exceptionHandling(exception -> exception
                        .accessDeniedHandler(accessDeniedExceptionHandler)
                        .authenticationEntryPoint(authenticationEntryPointHandler))
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilter(new JwtFilter(authenticationManager(), stringRedisTemplate, sysAuthConfiguration, jwtUtils))
                .csrf(AbstractHttpConfigurer::disable)
                .cors(AbstractHttpConfigurer::disable);
        return http.build();
    }
}

